package org.gbif.agi.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.appfuse.service.GenericManager;
import org.gbif.agi.model.Algorithm;
import org.appfuse.webapp.action.BaseAction;

import java.util.List;

public class AlgorithmAction extends BaseAction implements Preparable {
    private GenericManager<Algorithm, Long> algorithmManager;
    private List algorithms;
    private Algorithm algorithm;
    private Long  id;

    public void setAlgorithmManager(GenericManager<Algorithm, Long> algorithmManager) {
        this.algorithmManager = algorithmManager;
    }

    public List getAlgorithms() {
        return algorithms;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String algorithmId = getRequest().getParameter("algorithm.id");
            if (algorithmId != null && !algorithmId.equals("")) {
                algorithm = algorithmManager.get(new Long(algorithmId));
            }
        }
    }

    public String list() {
        algorithms = algorithmManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public Algorithm getAlgorithm() {
        return algorithm;
    }

    public void setAlgorithm(Algorithm algorithm) {
        this.algorithm = algorithm;
    }

    public String delete() {
        algorithmManager.remove(algorithm.getId());
        saveMessage(getText("algorithm.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            algorithm = algorithmManager.get(id);
        } else {
            algorithm = new Algorithm();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (algorithm.getId() == null);

        algorithmManager.save(algorithm);

        String key = (isNew) ? "algorithm.added" : "algorithm.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}